#ifndef LANAUDIOSERVER_H
#define LANAUDIOSERVER_H

#include <QtCore>
class TextSpeak;
class QHttpServer;
class QHttpServerRequest;
class QHttpResponse;
class AudioFile;

struct MpegtsInfo {
    QByteArray bytes;
    float duration;
    QString fileName;
};

class LanAudioServer;
class Converter : public QThread {
    Q_OBJECT
public:
    ~Converter() {
        needBreak_ = true;
        qDebug() << __FUNCTION__;
        this->wait();
    }
    Converter(LanAudioServer *server) : needBreak_(false),  totalTimestamp_(0.0f), server_(server) {
    }
    void push(const QByteArray &data, const QString &text) {
        QMutexLocker locker(&mutex_);
        qDebug() << "cache:" << text;
        caches_.append(QPair<QByteArray, QString>(data, text));
    }

protected:
    void run();

private:
    bool needBreak_;
    float totalTimestamp_;
    QMutex mutex_;
    QList<QPair<QByteArray, QString> > caches_;
    LanAudioServer *server_;
};

class LanAudioServer : public QThread
{
    Q_OBJECT
public:
    LanAudioServer(TextSpeak *speak);
    ~LanAudioServer();

    void pushMpegTs(const QByteArray &mdat, float duration);

Q_SIGNALS:
    void doStartRequest();
    void doResponed();

public Q_SLOTS:
    void onResponseBytes(const QByteArray &data, const QString &text);

private Q_SLOTS:
    void onInit();
    void onRelease();
    void onRequest(QHttpServerRequest *request, QHttpResponse *response);
    void onHttpDone();

private:
    QSharedPointer<QHttpServer> httpserver_;
    TextSpeak *speak_;

    QSharedPointer<AudioFile> audioFile_;
    QDateTime dateTimeOffset_;
    qint64 lastNeedWaiting_;

    QDateTime timeLast_;
    QByteArray byteCopyLast_;

    QMutex mutex_;
    int signIndex_;
    QList<MpegtsInfo> bytesTsList_;
    bool isPlaying_;

    Converter converter_;
};

#endif // LANAUDIOSERVER_H
